package platformlog_logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddClusterInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAddClusterInfoLogic 新建集群
func NewAddClusterInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddClusterInfoLogic {
	return &AddClusterInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddClusterInfoLogic) AddClusterInfo(req *types.AddClusterInfoRequest) (resp *types.ClusterInfoResponse, err error) {
	var checkExistSQL string
	var insertSQL string
	var tableName string

	if l.svcCtx.Config.UseMysql {
		tableName = l.svcCtx.Config.Mysql.Tables.ClusterInfo
	} else {
		tableName = l.svcCtx.Config.SQLite.Tables.ClusterInfo
	}

	checkExistSQL = fmt.Sprintf(`SELECT EXISTS(SELECT 1 FROM %s WHERE cluster_id = ?)`, tableName)
	insertSQL = fmt.Sprintf(`
        INSERT INTO %s (cluster_id, cluster_name, node_count, cluster_version, status, description, owner, region)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, tableName)

	// 开始事务
	err = l.svcCtx.Conn.Transact(func(session sqlx.Session) error {
		return l.transactAddClusterInfo(session, req.ClusterInfos, checkExistSQL, insertSQL)
	})

	if err != nil {
		return &types.ClusterInfoResponse{
			Code:    500,
			Message: fmt.Sprintf("集群信息创建失败: %v", err),
		}, err
	}

	return &types.ClusterInfoResponse{
		Code:    200,
		Message: "集群信息创建成功",
		Data:    req.ClusterInfos,
	}, nil
}

func (l *AddClusterInfoLogic) transactAddClusterInfo(session sqlx.Session, clusterInfos []types.ClusterInfo, checkExistSQL, insertSQL string) error {
	for _, info := range clusterInfos {

		var exists bool
		err := session.QueryRow(&exists, checkExistSQL, info.ClusterID)
		if err != nil {
			return fmt.Errorf("检查cluster_id存在失败: %w", err)
		}
		if exists {
			return errors.New("cluster_id已存在: " + info.ClusterID)
		}
		// 插入新的cluster_info记录
		_, err = session.Exec(insertSQL,
			info.ClusterID, info.ClusterName, info.NodeCount, info.ClusterVersion, info.Status, info.Description, info.Owner, info.Region)
		if err != nil {
			return fmt.Errorf("插入cluster_info失败: %w", err)
		}
	}
	return nil
}
